package com.xinqi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinqi.bean.Follow;
import com.xinqi.bean.User;
import com.xinqi.common.R;
import com.xinqi.mapper.FollowMapper;
import com.xinqi.service.FollowService;
import com.xinqi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author xin麒
 * @date 2023/3/2 23:58
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements FollowService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 查看当前博客是否被user点赞点赞
     * @param followUserId
     * @param userId
     * @return
     */
    @Override
    public R isFollow(Long followUserId, Long userId) {
        Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        return R.success(count > 0);
    }

    @Override
    public R follow(Long followUserId, boolean isFollow, Long userId) {
        String key = "follows:" + userId;
        if (isFollow){
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean isSuccess = save(follow);
            if (isSuccess) stringRedisTemplate.opsForSet().add(key,followUserId.toString());
        }else {
            boolean isSuccess = remove(new QueryWrapper<Follow>().eq("user_id",userId).eq("follow_user_id",followUserId));
            if (isSuccess) stringRedisTemplate.opsForSet().remove(key,followUserId.toString());
        }
        return R.success();
    }

    @Autowired
    private UserService userService;
    @Override
    public R followCommons(Long id, Long userId) {
        String myKey = "follows:" + userId;
        String otherkey = "follows:" + id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(myKey, otherkey);
        if (intersect == null || intersect.isEmpty()) return R.success(Collections.emptyList());

        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());

        List<User> users = userService.listByIds(ids);

        return R.success(users);
    }
}
